<script setup>
import {computed, onMounted, reactive, ref} from "vue";
import Export from "@/views/achievement/Export.vue";
import ResultItem from "@/views/achievement/ResultItem.vue";
import {onBeforeRouteUpdate} from "vue-router";
import {exportFile, getAllAchievement, searchAchievements} from "@/api/achievement";
import {SUCCESS} from "@/core/constants/HttpStatus";
import {ElMessage} from "element-plus";
import SideBar from "@/components/SideBar.vue";

// 成果主题type
let { type } = defineProps({
  type: String,
});
function mapTypeToEnum(typeName) {
  switch (typeName) {
    case "contest":
      return "0";
    case "patent":
      return "1";
    case "soft":
      return "2";
    case "paper":
      return "3";
    case "project":
      return "4";
  }
}
let typeEnum = ref(mapTypeToEnum(type));
// console.log(typeEnum);
onBeforeRouteUpdate((to, from, next) => {
  console.log(to);
  const fullPath = to.fullPath;
  const typeName = fullPath.split("/")[3];
  console.log("@@type", typeName);
  typeEnum.value = mapTypeToEnum(typeName);
  fetchAllAchievements();
  next();
});

const resultMenu = {
  title: "实践成果",
  path: "/achievement/result",
  children: [
    {
      id: 1,
      title: "竞赛",
      path: "/contest",
      icon: "icon-jiangpai-shi",
    },
    {
      id: 2,
      title: "专利",
      path: "/patent",
      icon: "icon-zhuanli",
    },
    {
      id: 3,
      title: "软著",
      path: "/soft",
      icon: "icon-ruanzhuyuce",
    },
    {
      id: 4,
      title: "论文",
      path: "/paper",
      icon: "icon-lunwenguanli",
    },
    {
      id: 5,
      title: "项目",
      path: "/project",
      icon: "icon-xiangmu",
    },
  ],
};

// 控制分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchAllAchievements();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchAllAchievements();
};
const fetchAllAchievements = async () => {
  try {
    const res = await getAllAchievement(
      typeEnum.value,
      currentPage.value,
      pageSize.value
    );
    const { code, data, msg } = res.data;
    if (code != SUCCESS) {
      throw new Error(msg);
    }
    itemList.value = data.records;
    total.value = Number(data.total);
  } catch (error) {
    ElMessage.error(error.message || "成果数据请求失败");
  }
};
const searchTitleList = ["项目名", "指导老师", "项目持有者"];
const conditionList = ["AND", "OR", "NOT"];
const searchForm = reactive({
  searchKeyWord: "",
  searchTitle: searchTitleList[0],
  connection1: conditionList[0],
  connection2: conditionList[0],
  startDate: null,
  endDate: null,
  type: 0,
});
const handleSearchAchievements = async () => {
  const searchData = {
    ...searchForm,
    type: typeEnum.value,
    startDate: searchForm.startDate?.toISOString().slice(0, 10),
    endDate: searchForm.endDate?.toISOString().slice(0, 10),
  };
  try {
    const res = await searchAchievements(
      searchData,
      currentPage.value,
      pageSize.value
    );
    const { code, data, msg } = res.data;
    if (code != SUCCESS) {
      throw new Error(msg);
    }
    itemList.value = data.records;
    total.value = Number(data.total);
  } catch (error) {
    ElMessage.error(error.message || "搜索失败");
  }
};
//重置按钮
const reset = () => {
  searchForm.searchKeyWord = "";
  searchForm.searchTitle = searchTitleList[0];
  searchForm.connection1 = conditionList[0];
  searchForm.connection2 = conditionList[0];
  searchForm.startDate = null;
  searchForm.endDate = null;
  searchForm.type = 0;
  // 重新请求？
};

//列表显示数据
const itemList = ref([]);
// 选中成果id列表
const selectedIds = ref([]);
// 选中成果
const selectId = (ids) => {
  selectedIds.value = ids;
  console.log("选中成果", ids);
};
// 导出数据
const exportList = computed(() => {
  return itemList.value.filter((item) => selectedIds.value.includes(item.id));
});
//导出表格弹窗
const exportDlgRef = ref(null);
//打开导出预览框
const handleExport = () => {
  exportDlgRef.value.openDialog();
};
const downloadFile = (data, fileName) => {
  if (!data) {
    return
  }
  const link = document.createElement('a');
  let blob = new Blob([data], {type: 'application/zip'});
  link.style.display = 'none';
  link.href = URL.createObjectURL(blob);

  link.setAttribute('download', fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const handleDownload = async (id) => {
  console.log(id);
  try {
    const res = await exportFile(id);
    console.log(res);
    const {type} = res.data;
    if(type == "application/json") {
      let reader = new FileReader();
      reader.readAsText(res.data);
      reader.onload = e => {
        const errResult = JSON.parse(e.target.result);
        const {msg} = errResult;
        ElMessage.error(msg || "附件下载失败");
      }
      return;
    }
    let fileNameCode = res.headers['content-disposition'].split(";")[1].split("=")[1];
    let fileName = decodeURIComponent(fileNameCode);
    console.log(fileName)
    downloadFile(res.data, fileName);
    ElMessage.success("附件下载成功");
  } catch (e) {
    ElMessage.error("附件下载失败");
  }
}

onMounted(() => {
  fetchAllAchievements()
});

const resultItemRef = ref(null);
const clearSelection = () => {
  resultItemRef.value.clearSelection();
}

</script>

<template>
  <div class="result">
    <SideBar :menuData="resultMenu"></SideBar>

    <div class="rightBox">
      <div class="rightBox-topBox">
        <div class="selectBox">
          <el-form :model="searchForm" class="searchForm">
            <el-form-item class="firstLine">
              <el-input
                v-model="searchForm.searchKeyWord"
                placeholder="Please input"
                class="input-with-select"
                style="width: 100%"
              >
                <template #prepend>
                  <el-select
                    v-model="searchForm.searchTitle"
                    style="width: 130px"
                  >
                    <el-option
                      v-for="(name, idx) in searchTitleList"
                      :key="idx"
                      :label="name"
                      :value="name"
                    />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="secondLine">
              <el-select v-model="searchForm.connection1" style="width: 80px">
                <el-option
                  v-for="(name, idx) in conditionList"
                  :key="idx"
                  :label="name"
                  :value="name"
                />
              </el-select>
              <el-form-item
                label="时间范围:"
                class="sencondLineRight"
                sytle="width:100%"
              >
                <el-col :span="11">
                  <el-date-picker
                    v-model="searchForm.startDate"
                    type="date"
                    placeholder="Pick a date"
                  />
                </el-col>
                <el-col :span="2" class="text-center">
                  <span class="text-gray-500">-</span>
                </el-col>
                <el-col :span="11">
                  <el-date-picker
                    v-model="searchForm.endDate"
                    placeholder="Pick a date"
                  />
                </el-col>
              </el-form-item>
            </el-form-item>
            <el-row class="buttonBox">
              <el-button @click="reset">重置条件</el-button>
              <el-button type="primary" @click="handleSearchAchievements"
                >检索</el-button
              >
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="rightBox-bottomBox">
        <ResultItem
          ref="resultItemRef"
          :item-list="itemList"
          @selectId="selectId"
          :handleExport="handleExport"
          :handleDownload="handleDownload"
        />
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="dialogBox">
        <Export
          :export-data="exportList"
          :selected-ids="selectedIds"
          ref="exportDlgRef"
          @clearSelection="clearSelection"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.result {
  display: flex;
}

//右侧整体布局
.rightBox {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding:50px 0px;
  .rightBox-topBox,
  .rightBox-centerBox,
  .rightBox-bottomBox {
    width: 90%;
    justify-content: center;
    align-items: center;
  }
}

.selectBox {
  width: 85%;
  margin:0px auto;
  padding: 30px 0px 20px 0px;
  border: 1px solid #d1d0d0;
  display: flex;
  justify-content: center;

  .searchForm {
    width: 90%;
    // 搜索栏第一行
    .firstLine {
      padding-left: 120px;
    }

    //搜索栏后两行布局
    .secondLine {
      width: 100%;

      .sencondLineRight {
        padding-left: 40px;

        .text-center {
          padding-left: 20px;
          font-size: 18px;
        }
      }
    }

    //搜索栏按钮行
    .buttonBox {
      border-top: 1px solid #d1d0d0;
      padding-top: 15px;
      display: flex;
      justify-content: center;
    }
  }
}

.dialogBox {
  width: 100%;
  background-color: #1e9ab5;
}
</style>
